package com.deng.template.common.jwt;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;

/**
 * @author Deng
 * @describe jwt工具类
 * @date 2022/10/31
 */
public class JwtUtil {

    private JwtUtil(){}

    private static final String secretKey = "gasdufsdfwhjerqwwqecsdfASFDASD";

    /**
     * 生成token
     * @param expiresDate 过期时间
     * @param json 实体
     * @param secretKey 加密盐
     * @return 加密
     */
    public static String generateJwtToken(Date expiresDate, JSONObject json, String secretKey) {
        // Header
        JWTCreator.Builder builder = JWT.create().withHeader(new HashMap<>());
        // Payload
        json.keySet().forEach( item -> builder.withClaim(item, json.getString(item)) );
        // 过期时间
        builder.withExpiresAt(expiresDate);
        // 签名用的secret
        return builder.sign(Algorithm.HMAC256(secretKey));
    }
    /**
     * 生成token
     * @param expiresDate 过期时间
     * @param json 实体
     * @return 加密
     */
    public static String generateJwtToken(Date expiresDate, JSONObject json) {
        return generateJwtToken(expiresDate, json, secretKey);
    }

    /**
     * 获取header
     * @param jwtToken token
     * @return header
     */
    public static String getHeader(String jwtToken){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
        return decodedJWT.getHeader();
    }

    /**
     * 判断是否有效
     * @param jwtToken token
     * @param time 时间
     * @return true / false
     */
    public static Boolean getExpires(String jwtToken, Date time){
        return getExpires(jwtToken, time, secretKey);
    }

    /**
     * 判断是否有效
     * @param jwtToken token
     * @param time 时间
     * @param secretKey 加密盐
     * @return true / false
     */
    public static Boolean getExpires(String jwtToken, Date time, String secretKey) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
        Date expires = decodedJWT.getExpiresAt();
        return expires.after(time) || expires == time;
    }

    public static Date getExpiresTime(String jwtToken, String secretKey) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
        return decodedJWT.getExpiresAt();
    }
}
